package com.tencent.wework.list.easy

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import com.tencent.wework.list.BaseListFragment
import com.tencent.wework.list.BaseRecyclerCell
import com.tencent.wework.list.LoadMoreDirection
import kotlinx.android.synthetic.main.base_list_fragment.*

/**
 * Created by huangwei on 2019/5/28.
 */
abstract class EasyListFragment<DATA,VM: EasyViewModel<DATA>>: BaseListFragment(){

    protected lateinit var viewModel:VM
    protected var offset:Any?=null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }
    abstract fun initViewModel():VM

    override fun initData() {
        viewModel = initViewModel()
        viewModel.data.observe(this, Observer<EasyDataWrapper<DATA>> {
            onObserver(it)
        })
        super.initData()
    }
    override fun onDataRefresh() {
        viewModel.requestData()
    }

    private fun onObserver(data:EasyDataWrapper<DATA>){
        activity?.runOnUiThread{
            val list = createCells(data.data)
            var scrollToBottom = false
            if(data.isLoadMore){
                adapter.appendCells(list,loadMoreDirection)
            }else{
                adapter.set(list)
                scrollToBottom = loadMoreDirection == LoadMoreDirection.TOP
            }
            offset = getOffset(data.data,data.isLoadMore)
            hasMoreData = !checkNoMore(data.data,data.isLoadMore)
            if(!hasMoreData){
                adapter.hideLoadingMore()
                adapter.showNoMoreContent(loadMoreDirection)
            }
            if(scrollToBottom){
                recyclerView.post { recyclerView.scrollToPosition(adapter.itemCount-1) }
            }
        }
    }

    /**
     * 实现loadMore功能用
     */
    open fun getOffset(data:DATA,fromLoadMore:Boolean):Any?{
        return null
    }

    /**
     * 实现loadMore功能用
     */
    open fun checkNoMore(data:DATA,fromLoadMore:Boolean):Boolean{
        return true
    }

    protected abstract fun createCells(data:DATA):List<BaseRecyclerCell<out Any>>

    override fun onLoadMore() {
        viewModel.loadMoreData(offset)
    }
}

